<template>
  <vxe-grid
      size="medium"
    :class="{'grid-bsolute-tools':isAbsolute}"
    :style="{ padding: styleType ? '10px 10px 0px 10px' : '0' }"
    ref="xGrid"
    round
    @toolbar-tool-click="toolbarButtonClickEvent"
    @current-change="currentChange"
    @page-change="pageChange"
    @form-reset="formReset"
    @toolbar-button-click="toolbarButtonClickEvent"
    v-bind="gridOptions"
    :checkbox-config="checkboxConfig"
    :export-config="{
      columns: getExportColumns,
      isFooter: true,
      original: false,
    }"
    @cell-dblclick="cellClick"
    @radio-change="radioChange"
    @scroll="scrollList"
    @checkbox-change="checkboxChange"
    @checkbox-all="selectAllEvent"
  >
  <!-- 年度 -->
  <template #slotsYear="{ data,property}">
          <vxe-input v-model="data[property]" 
          style="width:100%"
            label-format="yyyy"
            value-format="yyyy"
            placeholder="选择年度"
            clearable
              size="medium"
            type="year" transfer></vxe-input>
    </template>
      <!-- 开始日期 -->
  <template #slotsDate="{ data,property}">
      <vxe-input v-model="data[property]" 
          style="width:100%"
            label-format="yyyy-MM-dd"
            value-format="yyyy-MM-dd 00:00:00"
            placeholder="选择时间"
            clearable
              size="medium"
            type="date" transfer></vxe-input>
    </template>
    <template #dateRange="{ data,property }">
      <el-date-picker
          v-model="data[property]"
          style="width:100%"
          value-format="yyyy-MM-dd 00:00:00"
          type="daterange"
          size="small"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
    </template>
    <template #select="{ data,property }">
      <el-cascader style="width:100%"
          v-model="data[property]" 
          size="small"
          :options="selectTreeList"
          filterable
          clearable
          :props="{
              children: 'children',
              label: 'name',
              value:'categoryId'}">
        </el-cascader> 
    </template>
    <!--使用 top 插槽-->
    <template #top>
      <slot name="top"></slot>
    </template>
    <!--使用 bottom 插槽-->
    <template #bottom>
      <slot name="bottom"></slot>
    </template>
    <template #form v-if="openForm">
      <slot name="form"></slot>
    </template>
    <template #btns>
      <slot name="btns"></slot>
    </template>
    <!-- 操作栏 -->
    <template #actions="{ row, rowIndex }">
      <slot name="actions" :row="row" :rowIndex="rowIndex"> </slot>
    </template>
  </vxe-grid>
</template>

<script>
import { getListDataPage } from "@/api/queryVxegrid";
import store from '@/store'
export default {
  props: {
    styleType: {
      type: Boolean,
      default: true,
    },
    isAbsolute: {
      type: Boolean,
      default: false,
    },
    tableHeight: {
      type: Number | String,
      default: "auto",
    },
    toolbarConfig: {
      type: Boolean,
      default: false,
    },
    refresh: {
      //刷新
      type: Boolean,
      default: true,
    },
    import: {
      //导入
      type: Boolean,
      default: false,
    },
    export: {
      //导出
      type: Boolean,
      default: false,
    },
    print: {
      //打印
      type: Boolean,
      default: false,
    },
    zoom: {
      //全屏
      type: Boolean,
      default: true,
    },
    custom: {
      //选择列展示
      type: Boolean,
      default: true,
    },
    columnsList: {
      //列表数据
      type: Array,
      default() {
        return [];
      },
    },
    toolButtons: {
      //工具栏
      type: Array,
      default() {
        return [];
      },
    },
    tools: {
      //工具栏
      type: Array,
      default() {
        return [];
      },
    },
    openForm: {
      //是否启用表单插槽
      type: Boolean,
      default() {
        return true;
      },
    },
    formConfig: {
      //查询表单
      type: [Object, Boolean],
      default() {
        return {};
      },
    },
    apiUrl: {
      //接口地址
      type: String,
      default() {
        return null;
      },
    },
    method: {
      //请求方式
      type: String,
      default() {
        return "get";
      },
    },
    pageSize: {
      //分页默认行数
      type: Number,
      default: 15,
    },
    currentPage: {
      //分页默认页数
      type: Number,
      default: 1,
    },
    pagerConfig: {
      type: Boolean,
      default() {
        return true;
      },
    },
    showFooter: {
      type: Boolean,
      default() {
        return false;
      },
    },
    customList: {
      type: Array,
      default() {
        return [];
      },
    },
    footerList: {
      type: Array,
      default() {
        return [];
      },
    },
    footerType: {
      type: Boolean,
      default() {
        return true;
      },
    },
    showHeader: {
      type: Boolean,
      default() {
        return true;
      },
    },
    queryData: {
      type: Object,
      default() {
        return {};
      },
    },
    spanList: {
      type: Array,
      default() {
        return [];
      },
    },
    exportColumns: {
      type: Array,
      default() {
        return [];
      },
    },
    paramsType: {
      type: Boolean,
      default() {
        return true;
      },
    },
    totalFooter: {
      type: Array,
      default() {
        return [];
      },
    },
    pageSizes: {
      type: Array,
      default() {
        return [10, 15, 20, 30, 40, 50, 100];
      },
    },
    sortName: {
      type: String,
      default() {
        return null;
      },
    },
    checkboxConfig: {
      type: Object,
      default() {
        return {};
      },
    },
    treeConfig: {
      type: Object,
      default() {
        return {};
      },
    },
    selectTreeList:{
      type:Array,
      default(){
        return []
      }
    }
  },
  data() {
    return {};
  },
  computed: {
    getExportColumns() {
      return this.columnsList.filter((item) => {
        return item.type !== "checkbox";
      });
    },
    gridOptions() {
      let customList = this.customList;
      let footerList = this.footerList;
      let spanList = this.spanList;
      let totalFooter = this.totalFooter;
      let sortName = this.sortName;
      return {
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showHeader:this.showHeader,
        showOverflow: true,
        height: this.tableHeight,
        highlightHoverRow: true,
        highlightCurrentRow: true,
        keepSource: true,
        showFooter: this.showFooter,
        id: "gridId",
        rowId: "id",
        scrollY: {
          enabled: true,
        },
        customConfig: {
          storage: true,
          checkMethod({ column }) {
            if (customList.includes(column.property)) {
              return false;
            }
            return true;
          },
        },
        sortConfig: {
          trigger: "cell",
          remote: true,
          defaultSort: {
            field: sortName,
            order: "desc",
          },
        },
        treeConfig:this.treeConfig,
        filterConfig: {
          remote: true,
        },
        pagerConfig: {
          pageSize: this.pageSize,
          enabled: this.pagerConfig,
          pageSizes: this.pageSizes,
        },
        editConfig: {
          // 设置触发编辑为手动模式
          trigger: "click", //dblclick
          // 设置为整行编辑模式
          mode: "row",
          enabled: true,
          // 显示修改状态和新增状态
          showStatus: true,
          showUpdateStatus: true,
          showInsertStatus: true,
          autoClear: false,
          // 自定义可编辑列头的图标
          icon: "el-icon-edit",
        },
        formConfig: this.formConfig,
        toolbarConfig: this.toolbarConfig
          ? {
              buttons: this.getPermissioin(this.toolButtons),
              refresh: this.refresh, //刷新
              import: this.import, //导入
              export: this.export, //导出
              print: this.print, //打印
              zoom: this.zoom, //全屏
              custom: this.custom, //选择列展示
              tools: this.tools,
            }
          : false,
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: "result", // 配置响应结果列表字段
            total: "page.total", // 配置响应结果总页数字段
          },
          // 只接收Promise，不关心系实现方式
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: ({ page, sorts, filters, form }) => {
              return new Promise((resolve, reject) => {
                if (this.apiUrl) {
                  getListDataPage(
                    {
                      url: this.apiUrl,
                      method: this.method,
                      paramsType: this.paramsType,
                    },
                    {
                      page: page.currentPage,
                      limit: page.pageSize,
                      ...this.queryData,
                      ...form,
                    }
                  ).then((res) => {
                    if (this.pagerConfig) {
                        let list = res.rows || res.data;
                        //分页
                        resolve({
                          result: list,
                          page: {
                            total: res.total || 0,
                            pageNum: page.currentPage,
                            pageSize: page.pageSize,
                          },
                        });
                      
                    } else {
                      resolve(res.rows || res.data);
                    }
                    this.$emit("getData", res);
                    this.$emit("getFormData", {
                      pageNum: page.currentPage,
                      pageSize: page.pageSize,
                      ...this.queryData,
                      ...form,
                    });
                  });
                } else {
                  resolve({
                    result: [{}],
                    page: {
                      total: 0,
                      pageNum: page.currentPage,
                      pageSize: page.pageSize,
                    },
                  });
                }
              });
            },
          },
        },
        columns: this.columnsList,
        checkboxConfig: {
          reserve: true,
          highlight: true,
          range: true,
        },
        footerMethod({ columns, data }) {
          if (totalFooter.length > 0) {
            data = [totalFooter[totalFooter.length - 1]];
          }
          function sumNum(list, field) {
            let count = 0;
   
            return count;
          }
          return [
            columns.map((column, columnIndex) => {
              if (columnIndex === 0) {
                return "总计";
              }
              if (
                footerList.includes(column.property) &&column.property != undefined ) {
                  return Number(Number(sumNum(data, column.property)).toFixed(2));
              }
              return "";
            }),
          ];
        },
        spanMethod({ row, _rowIndex, column, visibleData }) {
          const fields = spanList;
          function getValueByData(obj, path) {
            let paths = path.split(".");
            let res = obj;
            let prop;
            while ((prop = paths.shift())) {
              if (res[prop]) {
                res = res[prop];
              }
            }
            return res;
          }
          if (column.property && column.property.indexOf("[") < 0) {
            const cellValue = getValueByData(row, column.property);
            if (cellValue && fields.includes(column.property)) {
              const prevRow = visibleData[_rowIndex - 1];
              let nextRow = visibleData[_rowIndex + 1];
              if (
                prevRow &&
                getValueByData(prevRow, column.property) === cellValue
              ) {
                return { rowspan: 0, colspan: 0 };
              } else {
                let countRowspan = 1;
                while (
                  nextRow &&
                  getValueByData(nextRow, column.property) === cellValue
                ) {
                  nextRow = visibleData[++countRowspan + _rowIndex];
                }
                if (countRowspan > 1) {
                  return { rowspan: countRowspan, colspan: 1 };
                }
              }
            }
          }
        },
      };
    },
  },
  methods: {
    checkboxChange(e) { 
      this.$emit("checkboxChange", e.records);
    },
    selectAllEvent(e) {
      this.$emit("selectAllEvent", e.records);
    },
    btnExport() {
      this.$refs.xGrid.openExport();
    },
    btnExportData() {
      this.$refs.xGrid.exportData({
        filename: "Order details",
        sheetName: "Order details ( X02514645652 )",
        type: "pdf",
      });
    },
    setActiveRow(item) {
      this.$refs.xGrid.setActiveRow(item);
    },
    getRecordset() {
      return this.$refs.xGrid.getRecordset();
    },
    radioChange(e) {
      this.$emit("radioChange", e.row);
    },
    cellClick(e) {
      this.$emit("cellClick", e.row);
    },
    removeRows(rows) {
      setTimeout(() => {
        this.$refs.xGrid.remove(rows);
      }, 50);
    },
    scrollList({
      type,
      scrollTop,
      scrollLeft,
      scrollHeight,
      scrollWidth,
      bodyWidth,
      bodyHeight,
      isX,
      isY,
      $event,
    }) {
      this.$emit("scrollList", {
        type,
        scrollTop,
        scrollLeft,
        scrollHeight,
        scrollWidth,
        bodyWidth,
        bodyHeight,
        isX,
        isY,
        $event,
      });
    },
    changeData(form) {
      let formData = {
        ...this.$refs.xGrid.formData,
        ...form,
      };
      this.$refs.xGrid.formData = formData;
      this.$refs.xGrid.commitProxy("query");
    },
    setAllTreeExpand() {
      this.$refs.xGrid.setAllTreeExpand(true)
    },
    clearTreeExpand() {
      this.$refs.xGrid.clearTreeExpand()
    },
    setAllRowExpand() {
      this.$refs.xGrid.setAllRowExpand(true)
    },
    clearRowExpand() {
      this.$refs.xGrid.clearRowExpand()
    },
    //table工具栏事件
    toolbarButtonClickEvent({ code }) {
      this.$emit("toolbarButtonClickEvent", code);
    },
    //from工具栏事件
    toolbarToolClickEvent({ code }) {
      this.$emit("toolbarToolClickEvent", code);
    },
    currentChange(data) {
      this.$emit("currentChange", data.row);
      this.$emit("changeIndex", data.rowIndex);
    },
    formReset(data){
      for(let key in data.data){
        data.data[key]=null
      }
    },
    pageChange({ pageSize, currentPage }) {
      this.$emit("pageChange", {
        pageSize: pageSize,
        currentPage: currentPage,
      });
    },
    getPermissioin(btnList) {
      //按钮权限
      return btnList
      const permissionlist = store.getters && store.getters.permissions
      const all_permission = "*:*:*";
      return btnList
        .map((item) => {
          if (permissionlist[0]===all_permission || permissionlist.indexOf(item.has) >= 0 ||item.has=='*') {
            this.$set(item, "show", true);
          } else {
            this.$set(item, "show", false);
          }
          return item;
        })
        .filter((item) => {
          return item.show == true;
        });
    },
  },
};
</script>
<style>
.grid-bsolute-tools .vxe-grid--toolbar-wrapper{
  position:absolute;
  right:10px;
  top:10px;
  z-index:9;
}
</style>